package xyz.liut.ee.api

import jakarta.servlet.annotation.WebServlet
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import xyz.liut.ee.bean.FileBean
import xyz.liut.ee.req.realPath2Url
import xyz.liut.ee.resp.ResponseEntity
import xyz.liut.ee.resp.sendBy
import xyz.liut.ee.web.BaseServlet
import xyz.liut.ee.web.CONFIG_FILE_PATH
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths

@WebServlet("/download")
class Download : BaseServlet() {

    override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
        val queryName = req.getParameter("file")
        val contentDisposition = req.getParameter("cd")
        val contentType = req.getParameter("ct")
        val dir = File(CONFIG_FILE_PATH)
        if (queryName == null) {
            val entity: ResponseEntity<MutableList<FileBean>> = ResponseEntity()
            val result = mutableListOf<FileBean>()
            entity.data = result
            try {
                val files = dir.listFiles()
                files?.forEach {
                    val bean = FileBean()
                    bean.fileName = it.name
                    bean.url = realPath2Url(req, it.name)
                    bean.length = it.length()
                    result.add(bean)
                }
                entity.msg = "查找成功"
                entity.code = 200
            } catch (e: Exception) {
                e.printStackTrace()
                entity.msg = e.javaClass.simpleName + " " + e.message
                entity.code = -100
            }
            entity.sendBy(resp)
        } else {
            val file = File(dir.toString() + File.separator + queryName)
            if (file.exists()) {
                resp.contentType = contentType ?: "application/x-silverlight-app" //设置头信息
                resp.setContentLengthLong(file.length()) //设置头信息
                resp.setHeader("Content-Disposition", "${contentDisposition ?: "attachment"};filename=\"$queryName\"")
                resp.outputStream.use {
                    Files.copy(Paths.get(dir.toString() + File.separator + queryName), it)
                }
            } else {
                resp.sendRedirect("/api/404")
            }
        }
    }


}
